<template>
  <h2>当前求和为: {{ sum }}</h2>
  <button @click="sum++">点我加1</button>
  <hr />
  <h2>当前的信息为: {{ msg }}</h2>
  <button @click="msg += '!'">点我加1</button>
  <hr />
  <h2>姓名:{{ person.name }}</h2>
  <h2>年龄:{{ person.age }}</h2>
  <h2>薪资:{{ person.job.j1.salary }}K</h2>
  <button @click="person.name += '~'">修改姓名</button>
  <button @click="person.age++">修改年龄</button>
  <button @click="person.job.j1.salary++">涨薪</button>

  <h1>watchEffect的值: {{ res }}</h1>
</template>

<script>
import { ref, reactive, watchEffect } from "vue"; // ref处理基本类型数据  reactive处理引用类型数据
export default {
  name: "demo",
  setup() {
    // 数据
    let sum = ref(0);
    let msg = ref("hello");
    let res = ref(null)
    let person = reactive({
      name: "张三",
      age: 18,
      job: {
        j1: {
          salary: 20,
        },
      },
    });

    // 监视
    // watch(sum, (newVal, oldVal) => {
    //   console.log("sum的值变了", "newVal===", newVal, "oldVal===", oldVal);
    // });

    // 0  20  watchEffct所指定的回调执行了
    /**
     * watch:既要指明监视的属性,也要指明监视的回调
     * watchEffct: 不用指明监视哪个属性,监视的回调中用到哪个属性,那就监视哪个属性
     * watchEffct有点像computed:
     *    1.computed注重的是计算出来的值(回调函数的返回值),所以必须要写返回值
     *    2.watchEffect更注重的是过程(回调函数的函数体),所以不用写返回值
     */
    watchEffect(()=>{
      const x1 = sum.value
      console.log(x1) // 0
      const x2 = person.job.j1.salary
      console.log(x2) // 20
      console.log('watchEffct所指定的回调执行了')

      res.value = x1 + x2 // 初始化为20  x1/x2增加  res也会跟着增加
    })

    return {
      sum,
      msg,
      res,
      person
    };
  },
};
</script>


